package com.centaline.androidsalesblog.activities.entrust;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.android.volley.VolleyError;
import com.bumptech.glide.BitmapTypeRequest;
import com.bumptech.glide.DrawableRequestBuilder;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.mine.BindingPhoneActivity;
import com.centaline.androidsalesblog.activities.mine.LoginActivity;
import com.centaline.androidsalesblog.activities.news.ChatActivity;
import com.centaline.androidsalesblog.activities.sale.EsfDealHistoryActivity;
import com.centaline.androidsalesblog.activities.sale.EsfEstateDetailActivity;
import com.centaline.androidsalesblog.activities.sale.StaffDetailActivity;
import com.centaline.androidsalesblog.api.sale.AutoEstateApi;
import com.centaline.androidsalesblog.api.sale.EsfDealHistoryApi;
import com.centaline.androidsalesblog.api.sale.EstEstateDetailApi;
import com.centaline.androidsalesblog.api.sale.PostInternalApi;
import com.centaline.androidsalesblog.api.sale.StaffApi;
import com.centaline.androidsalesblog.api.usercenter.EntrustInfoListRequestApi;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.model.businissobject.AutoEstateBo;
import com.centaline.androidsalesblog.model.businissobject.EsfDealHistoryBo;
import com.centaline.androidsalesblog.model.businissobject.EstateDataModelBo;
import com.centaline.androidsalesblog.model.businissobject.MyEntrustInfoBo;
import com.centaline.androidsalesblog.model.businissobject.PostInternalBo;
import com.centaline.androidsalesblog.model.databaseobject.BizUnitDo;
import com.centaline.androidsalesblog.model.databaseobject.StaffDo;
import com.centaline.androidsalesblog.model.databaseobject.UserDo;
import com.centaline.androidsalesblog.model.responseobject.AutoEstateRo;
import com.centaline.androidsalesblog.model.responseobject.EntrustInfoListRo;
import com.centaline.androidsalesblog.model.responseobject.EsfDealHistoryRo;
import com.centaline.androidsalesblog.model.responseobject.EsfEstateDetailRo;
import com.centaline.androidsalesblog.model.responseobject.PostInternalRo;
import com.centaline.androidsalesblog.model.responseobject.StaffRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.utils.ContactUtil;
import com.centaline.androidsalesblog.utils.DateUtil;
import com.centaline.androidsalesblog.utils.PriceUtil;
import com.centaline.androidsalesblog.utils.ResponseCheck;
import com.centaline.androidsalesblog.utils.RongUserIdUtil;
import com.centaline.androidsalesblog.widgets.chart.SaleLineChart;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.glide.RoundImageViewTarget;
import com.centanet.framework.interfaces.IResponseListener;
import com.trello.rxlifecycle.ActivityEvent;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 查看我的房源
 * Created by Lihq on 16/3/14.
 */
public class MyHouseResourceActivity extends BaseActivity implements View.OnClickListener {
    private AppCompatImageView img_estate;
    private AppCompatTextView atv_no_data, atv_estate, atv_name, atv_house_type, atv_bargain_price, atv_signed_date,
            atv_estate_date, atv_price_avg, atv_before_price, atv_price, atv_im, atv_msg, atv_phone, atv_bargain_number;
    private ImageView img_staff;
    private RelativeLayout rl_bargain_history, rl_deal_history;
    private LinearLayout ll_looking_house_record;
    private ViewStub vs_line;
    private ScrollView sv_data;

    private EntrustInfoListRequestApi entrustInfoListRequestApi;
    private EsfDealHistoryApi esfDealHistoryApi;
    private EstEstateDetailApi estEstateDetailApi;
    private StaffApi staffApi;
    private AutoEstateApi autoEstateApi;
    private int index = 0;
    private int number = 0;
    private String cestCode;

    private StaffDo staffDo;
    private String staffNo;
    private ArrayList<MyEntrustInfoBo> entrustInfoList;
    private String entrustType;
    private String userId;
    private String status;
    private EstateDataModelBo estateDataModelBo;
    private boolean isFirstChart = true;
    private SaleLineChart saleLineChart;
    private BitmapTypeRequest<String> mBitmapTypeRequest;
    private DrawableRequestBuilder<String> requestBuilder;
    private String bigCode;
    private String extCode;


    @Override
    protected int setLayoutId() {
        return R.layout.activity_my_house_resource;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar(R.string.title_my_house_resource);
        img_estate = (AppCompatImageView) findViewById(R.id.img_estate);
        atv_estate = (AppCompatTextView) findViewById(R.id.atv_estate);
        atv_name = (AppCompatTextView) findViewById(R.id.atv_name);
        atv_house_type = (AppCompatTextView) findViewById(R.id.atv_house_type);
        atv_bargain_price = (AppCompatTextView) findViewById(R.id.atv_bargain_price);
        atv_signed_date = (AppCompatTextView) findViewById(R.id.atv_signed_date);
        atv_estate_date = (AppCompatTextView) findViewById(R.id.atv_estate_date);
        atv_price_avg = (AppCompatTextView) findViewById(R.id.atv_price_avg);
        atv_before_price = (AppCompatTextView) findViewById(R.id.atv_before_price);
        atv_price = (AppCompatTextView) findViewById(R.id.atv_price);
        atv_msg = (AppCompatTextView) findViewById(R.id.atv_msg);
        atv_im = (AppCompatTextView) findViewById(R.id.atv_im);
        atv_phone = (AppCompatTextView) findViewById(R.id.atv_phone);
        atv_bargain_number = (AppCompatTextView) findViewById(R.id.atv_bargain_number);
        atv_no_data = (AppCompatTextView) findViewById(R.id.atv_no_data);
        img_staff = (ImageView) findViewById(R.id.img_staff);
        rl_bargain_history = (RelativeLayout) findViewById(R.id.rl_bargain_history);
        rl_deal_history = (RelativeLayout) findViewById(R.id.rl_deal_history);
        ll_looking_house_record = (LinearLayout) findViewById(R.id.ll_looking_house_record);
        vs_line = (ViewStub) findViewById(R.id.vs_line);
        sv_data = (ScrollView) findViewById(R.id.sv_data);

    }

    @Override
    protected void initViews() {
        rl_bargain_history.setOnClickListener(this);
        img_staff.setOnClickListener(this);
        atv_msg.setOnClickListener(this);
        atv_im.setOnClickListener(this);
        atv_phone.setOnClickListener(this);
        mBitmapTypeRequest = GlideLoad.initRound(this);
        requestBuilder = GlideLoad.init(this);
        entrustType = getIntent().getStringExtra(ExtraConstant.EntrustType);
        bizUnit();
        checkLogin();
    }

    private void checkLogin() {
        if (AppConstant.IsLogin) {
            RxDataBase.getUser()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(this.<UserDo>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<UserDo>() {
                        @Override
                        public void call(UserDo userDo) {
                            if (userDo != null)
                                if (TextUtils.isEmpty(userDo.getPhone())) {
                                    startActivityForResult(new Intent(MyHouseResourceActivity.this,
                                                    BindingPhoneActivity.class),
                                            CommonConstant.REQ_BIND_MOBILE);
                                } else {
                                    userId = userDo.getUserId();
                                    mainRequest();
                                    entrustInfoListRequestApi.setUserId(userId);
                                    entrustInfoListRequestApi.setCityCode(AppConstant.CityCode);
                                    entrustInfoListRequestApi.setEntrustType(entrustType);
                                    entrustInfoListRequestApi.setFirstIndex(0);
                                    entrustInfoListRequestApi.startRequest();
                                }
                        }
                    });
        } else {
            startActivityForResult(new Intent(this, LoginActivity.class), CommonConstant.REQ_LOGIN);
        }
    }


    private void mainRequest() {
        entrustInfoListRequestApi = new EntrustInfoListRequestApi(MyHouseResourceActivity.class, EntrustInfoListRo
                .class, new IResponseListener<EntrustInfoListRo>() {
            @Override
            public void onResponse(EntrustInfoListRo entrustInfoListRo) {
                entrustInfoList = entrustInfoListRo.getList();
                if (entrustInfoList == null || entrustInfoList.size() == 0) {
                    atv_no_data.setVisibility(View.VISIBLE);
                    sv_data.setVisibility(View.GONE);
                } else {
                    atv_no_data.setVisibility(View.GONE);
                    sv_data.setVisibility(View.VISIBLE);
                    invalidateOptionsMenu();
                    MyEntrustInfoBo myEntrustInfoBo = entrustInfoList.get(index);

                    status = myEntrustInfoBo.getStatus();
                    if (status.equals("待处理") || status.equals("")) {
                        ll_looking_house_record.setVisibility(View.GONE);
                        atv_estate_date.setText(
                                String.format(Locale.CHINA, "%s提交", getTime(myEntrustInfoBo.getCreateTime2() * 1000)));
                        double eprice = myEntrustInfoBo.getPriceTo();
                        double efprice = myEntrustInfoBo.getPriceFrom();
                        if (myEntrustInfoBo.getEntrustType().equals("出售")) {
                            if (efprice != 0 && eprice != 0) {
                                atv_before_price.setText(String.format(Locale.CHINA, "期望%.0f万-%.0f",
                                        efprice / 10000, eprice / 10000));
                            } else if (efprice == 0) {
                                atv_before_price.setText(eprice == 0 ? "" : String.format(Locale.CHINA, "期望%s万",
                                        (long) eprice / 10000));
                            } else {
                                atv_before_price.setText(String.format(Locale.CHINA, "期望%s万", (long) efprice / 10000));
                            }
                        } else {
                            if (efprice != 0 && eprice != 0) {
                                atv_before_price.setText(String.format(Locale.CHINA, "期望%.0f-%.0f元/月",
                                        efprice, eprice));
                            } else if (efprice == 0) {
                                atv_before_price.setText(eprice == 0 ? "" : String.format(Locale.CHINA, "期望%s元/月",
                                        (long) (eprice)));
                            } else {
                                atv_before_price.setText(String.format(Locale.CHINA, "期望%s元/月", (long) efprice));
                            }
                        }
                    } else {
                        ll_looking_house_record.setVisibility(View.VISIBLE);
                    }
                    if (!TextUtils.isEmpty(myEntrustInfoBo.getEstateCode())) {
                        cestCode = myEntrustInfoBo.getEstateCode();
                        historyRequest(cestCode, 0);
                        estateRequst(cestCode, 0);
                    } else {
                        estateCodeRequest(myEntrustInfoBo.getEstateName());
                    }
                    if (myEntrustInfoBo.getStaffNo() != "" && myEntrustInfoBo.getStaffNo() != null) {
                        staffRequest(myEntrustInfoBo.getStaffNo(), 0);
                    }
                    atv_estate.setText(myEntrustInfoBo.getEstateName());
                    atv_name.setText(myEntrustInfoBo.getStaffName());
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

    }

    private void estateCodeRequest(String estateName) {
        autoEstateApi = new AutoEstateApi(EstateSearchActivity.class, AutoEstateRo.class, new
                IResponseListener<AutoEstateRo>() {

                    @Override
                    public void onResponse(AutoEstateRo autoEstateRo) {
                        final ArrayList<AutoEstateBo> temp = autoEstateRo.getList();
                        if (temp != null && temp.size() != 0) {
                            cestCode = temp.get(0).getCestCode();
                            historyRequest(cestCode, 0);
                            estateRequst(cestCode, 0);
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        autoEstateApi.setKey(estateName);
        autoEstateApi.startRequest();
    }

    private void staffRequest(String staffNo, final int index) {
        staffApi = new StaffApi(StaffDetailActivity.class, StaffRo.class, new IResponseListener<StaffRo>() {
            @Override
            public void onResponse(StaffRo staffRo) {
                staffDo = staffRo.getStaffDo();
                if (staffDo != null) {
                    if (GlideLoad.needLoad(true)) {
                        mBitmapTypeRequest
                                .load(staffDo.getImgUrl())
                                .placeholder(R.drawable.ic_staff_default)
                                .error(R.drawable.ic_staff_default)
                                .centerCrop()
                                .into(new RoundImageViewTarget(img_staff));
                    } else {
                        mBitmapTypeRequest
                                .load("")
                                .placeholder(R.drawable.ic_staff_default)
                                .error(R.drawable.ic_staff_default)
                                .centerCrop()
                                .into(new RoundImageViewTarget(img_staff));
                    }
                    //绑定数据
                    entrustInfoList.get(index).setImgUrl(staffDo.getImgUrl());
                    entrustInfoList.get(index).setMobile(staffDo.getMobile());
                    entrustInfoList.get(index).setBigCode(staffDo.getBigCode());
                    entrustInfoList.get(index).setExtCode(staffDo.getExtCode());

                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                netWorkUnable();
            }
        });
        staffApi.setStaffNo(staffNo);
        staffApi.startRequest();
    }

    private void estateRequst(String cestCode, final int index) {
        estEstateDetailApi = new EstEstateDetailApi(EsfEstateDetailActivity.class, EsfEstateDetailRo.class,
                new IResponseListener<EsfEstateDetailRo>() {
                    private String imgUrl;

                    @Override
                    public void onResponse(EsfEstateDetailRo esfEstateDetailRo) {
                        if (ResponseCheck.check(esfEstateDetailRo) &&
                                esfEstateDetailRo.getEsfResultBo() != null &&
                                esfEstateDetailRo.getEsfResultBo().getEstateDataModelBos() != null) {
                            estateDataModelBo = esfEstateDetailRo.getEsfResultBo().getEstateDataModelBos().get(0);
                            otherRequest();
                            if (esfEstateDetailRo.getEsfResultBo().getEsfImgBos().size() != 0) {
                                imgUrl = esfEstateDetailRo.getEsfResultBo().getEsfImgBos().get(0).getText();
                            }
                            GlideLoad.load(new GlideLoad.Builder(requestBuilder, imgUrl)
                                    .placeHolder(R.drawable.ic_centa_square_logo)
                                    .error(R.drawable.ic_centa_square_logo)
                                    .openWifiSwitch()
                                    .into(img_estate));
                            //绑定数据
                            entrustInfoList.get(index).setCestImgUrl(imgUrl);
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        otherRequest();
                    }
                });
        estEstateDetailApi.setCestCode(cestCode);
        estEstateDetailApi.startRequest();
    }

    private void historyRequest(String cestCode, final int index) {
        esfDealHistoryApi = new EsfDealHistoryApi(EsfEstateDetailActivity.class, EsfDealHistoryRo.class,
                new IResponseListener<EsfDealHistoryRo>() {
                    @Override
                    public void onResponse(EsfDealHistoryRo esfDealHistoryRo) {
                        if (ResponseCheck.check(esfDealHistoryRo) &&
                                esfDealHistoryRo.getList() != null) {
                            final ArrayList<EsfDealHistoryBo> temp = esfDealHistoryRo.getList();
                            EsfDealHistoryBo esfDealHistoryBo = temp.get(0);
                            atv_bargain_number.setText(String.format(Locale.CHINA, "（%s）", esfDealHistoryRo.getTotal
                                    () + ""));
                            atv_house_type.setText(String.format(Locale.CHINA, "%s", esfDealHistoryBo.getHouseType()));
                            atv_bargain_price.setText(PriceUtil.dealPrice(esfDealHistoryBo.getDealPrice()));
                            atv_signed_date.setText(DateUtil.format(esfDealHistoryBo.getDealTime(),
                                    DateUtil.FORMAT1, DateUtil.FORMAT2));

                            //绑定数据
                            entrustInfoList.get(index).setTotal(esfDealHistoryRo.getTotal());
                            entrustInfoList.get(index).setHouseType(esfDealHistoryBo.getHouseType());
                            entrustInfoList.get(index).setDealPrice(PriceUtil.dealPrice(esfDealHistoryBo.getDealPrice
                                    ()));
                            entrustInfoList.get(index).setDealTime(DateUtil.format(esfDealHistoryBo.getDealTime(),
                                    DateUtil.FORMAT1, DateUtil.FORMAT2));
                        } else {
                            atv_bargain_number.setText("（0）");
                            atv_house_type.setText("");
                            atv_bargain_price.setText("");
                            atv_signed_date.setText("");
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        esfDealHistoryApi.setCestCode(cestCode);
        esfDealHistoryApi.setPageCount(1);
        esfDealHistoryApi.startRequest();
    }

    private void otherRequest() {
        //房价走势
        PostInternalApi postInternalApi = new PostInternalApi(EsfEstateDetailActivity.class, PostInternalRo.class,
                new IResponseListener<PostInternalRo>() {
                    @Override
                    public void onResponse(PostInternalRo postInternalRo) {
                        if (postInternalRo != null) {
                            ArrayList<PostInternalBo> postInternalBos = postInternalRo.getList();
                            if (postInternalBos != null &&
                                    postInternalBos.size() > 0) {
                                boolean show = false;
                                for (PostInternalBo postInternalBo : postInternalBos) {
                                    if (postInternalBo != null &&
                                            "estate".equalsIgnoreCase(postInternalBo.getType()) &&
                                            postInternalBo.getDealListBos() != null &&
                                            postInternalBo.getDealListBos().size() > 2) {
                                        show = true;
                                    }
                                }
                                if (show && vs_line != null) {
                                    if (isFirstChart) {
                                        vs_line.inflate();
                                    }
                                    rl_deal_history.setVisibility(View.VISIBLE);
                                    vs_line.setVisibility(View.VISIBLE);
                                    isFirstChart = false;
                                    saleLineChart = (SaleLineChart) findViewById(R.id.saleLineChart);
                                    if (saleLineChart != null) {
                                        saleLineChart.setPostInternalBos(estateDataModelBo.getSaleEstateBo()
                                                        .getC_estate(),
                                                postInternalBos);
                                        entrustInfoList.get(index).setC_estate(estateDataModelBo.getSaleEstateBo()
                                                .getC_estate());
                                        entrustInfoList.get(index).setPostInternalBos(postInternalBos);
                                        cancelLoadingDialog();
                                    }
                                } else {
                                    rl_deal_history.setVisibility(View.GONE);
                                    vs_line.setVisibility(View.GONE);
                                }
                            }
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        postInternalApi.setCestcode(cestCode);
        if (estateDataModelBo != null) {
            postInternalApi.setGscopeid(String.valueOf(estateDataModelBo.getSaleEstateBo().getGScopeId()));
            postInternalApi.startRequest();
        }
    }


    private void setText(LinearLayout ll, AppCompatTextView atv, String data) {
        if (TextUtils.isEmpty(data)) {
            ll.setVisibility(View.GONE);
            return;
        }
        atv.setText(data);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CommonConstant.REQ_LOGIN:
                case CommonConstant.REQ_BIND_MOBILE:
                    checkLogin();
                    break;
                default:
                    break;
            }
        } else {
            finish();
        }
    }

    private void refreshUi(int number, int index) {
        MyEntrustInfoBo myEntrustInfoBo = entrustInfoList.get(index);
        cestCode = myEntrustInfoBo.getEstateCode();
        staffNo = myEntrustInfoBo.getStaffNo();
        bigCode = entrustInfoList.get(index).getBigCode();
        extCode = entrustInfoList.get(index).getExtCode();
        atv_estate.setText(myEntrustInfoBo.getEstateName());
        atv_name.setText(myEntrustInfoBo.getStaffName());
        if (status.equals("待处理") || status.equals("")) {
            atv_before_price.setVisibility(View.VISIBLE);
            atv_price_avg.setVisibility(View.VISIBLE);
            atv_price.setVisibility(View.VISIBLE);
            atv_estate_date.setText(getTime(myEntrustInfoBo.getCreateTime2() * 1000) + "提交");
            double eprice = myEntrustInfoBo.getPriceTo();
            double efprice = myEntrustInfoBo.getPriceFrom();
            if (myEntrustInfoBo.getEntrustType().equals("出售")) {
                if (efprice != 0 && eprice != 0) {
                    atv_before_price.setText(String.format(Locale.CHINA, "期望%s万-", (long) efprice / 10000) + String
                            .format(Locale.CHINA, "%s万", (long) eprice / 10000));
                } else if (efprice == 0) {
                    atv_before_price.setText(eprice == 0 ? "" : String.format(Locale.CHINA, "期望%s万", (long) eprice /
                            10000));
                } else {
                    atv_before_price.setText(String.format(Locale.CHINA, "期望%s万", (long) efprice / 10000));
                }
            } else {
                if (efprice != 0 && eprice != 0) {
                    atv_before_price.setText(String.format(Locale.CHINA, "期望%s-", (long) efprice) + String.format
                            (Locale.CHINA, "%s元/月", (long) eprice));
                } else if (efprice == 0) {
                    atv_before_price.setText(eprice == 0 ? "" : String.format(Locale.CHINA, "期望%s元/月", (long)
                            (eprice)));
                } else {
                    atv_before_price.setText(String.format(Locale.CHINA, "期望%s元/月", (long) efprice));
                }
            }
        }
        if (index < number) {
            //加载成交历史数据
            atv_bargain_number.setText(String.format(Locale.CHINA, "（%s）", myEntrustInfoBo.getTotal() + ""));
            atv_house_type.setText(myEntrustInfoBo.getHouseType());
            atv_bargain_price.setText(myEntrustInfoBo.getDealPrice());
            atv_signed_date.setText(myEntrustInfoBo.getDealTime());
            //加载经纪人数据
            if (GlideLoad.needLoad(true)) {
                mBitmapTypeRequest
                        .load(myEntrustInfoBo.getImgUrl())
                        .placeholder(R.drawable.ic_staff_default)
                        .error(R.drawable.ic_staff_default)
                        .centerCrop()
                        .into(new RoundImageViewTarget(img_staff));
            } else {
                mBitmapTypeRequest
                        .load("")
                        .placeholder(R.drawable.ic_staff_default)
                        .error(R.drawable.ic_staff_default)
                        .centerCrop()
                        .into(new RoundImageViewTarget(img_staff));
            }
            //加载房源img数据
            GlideLoad.load(new GlideLoad.Builder(requestBuilder, myEntrustInfoBo
                    .getCestImgUrl())
                    .placeHolder(R.drawable.ic_centa_square_logo)
                    .error(R.drawable.ic_centa_square_logo)
                    .openWifiSwitch()
                    .into(img_estate));
            //加载图表1
            if (myEntrustInfoBo.getC_estate() == null || myEntrustInfoBo.getPostInternalBos() ==
                    null) {
                vs_line.setVisibility(View.GONE);
                rl_deal_history.setVisibility(View.GONE);
            } else {
                saleLineChart.setPostInternalBos(myEntrustInfoBo.getC_estate(),
                        myEntrustInfoBo.getPostInternalBos());
            }
        } else {
            staffRequest(staffNo, index);
            historyRequest(cestCode, index);
            estateRequst(cestCode, index);
        }
    }

    private String getTime(long time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(time);
        return format.format(date);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (entrustInfoList != null) {
            if (entrustInfoList.size() > 1) {
                getMenuInflater().inflate(R.menu.menu_up_down, menu);
            }
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            setResult(RESULT_OK);
            finish();
            return true;
        }
        if (entrustInfoList != null) {
            if (item.getItemId() == R.id.action_page_down) {

                if (index < entrustInfoList.size() - 1) {
                    index = index + 1;
                    if (number < index) {
                        number = index;
                    }
                    refreshUi(number, index);

                } else {
                    number = entrustInfoList.size() + 1;
                    refreshUi(number, index);
                }

            }
            if (item.getItemId() == R.id.action_page_up) {
                if (index > 0) {
                    index = index - 1;
                    refreshUi(entrustInfoList.size() + 1, index);
                }
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_bargain_history:
                startActivity(new Intent(this, EsfDealHistoryActivity.class)
                        .putExtra(ExtraConstant.CestCode, cestCode));
                break;
            case R.id.img_staff:
//                startActivity(new Intent(MyHouseResourceActivity.this, StaffDetailActivity.class)
//                        .putExtra(ExtraConstant.StaffNo, staffNo));
                break;
            case R.id.atv_im:
                startActivity(new Intent(this, ChatActivity.class)
                        .putExtra(ExtraConstant.TargetId, RongUserIdUtil.getSatffId(staffNo)));
                break;
            case R.id.atv_msg:
                ContactUtil.sendMsg(MyHouseResourceActivity.this, entrustInfoList.get(index).getMobile());
                break;
            case R.id.atv_phone:
                new AlertDialog.Builder(this)
                        .setMessage(String.format(Locale.CHINA, "拨打:%s,%s",
                                bigCode, extCode))
                        .setPositiveButton("拨打", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ContactUtil.dial(MyHouseResourceActivity.this, bigCode, extCode);
                                baiduEvent("Z1_1_Click");
                            }
                        }).setNegativeButton("取消", null)
                        .create()
                        .show();
                break;
            default:
                break;
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            setResult(RESULT_OK);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 获取配置信息
     */
    private void bizUnit() {
        RxDataBase.getBizUnit()
                .compose(this.<BizUnitDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BizUnitDo>() {
                    @Override
                    public void call(BizUnitDo bizUnitDo) {
                        atv_im.setVisibility(bizUnitDo.isShowTalk() ? View.VISIBLE : View.GONE);
                    }
                });
    }
}
